#include "bbh_config.h"

#include "bbh_level.h"

int  bbh_config_create(bbh_config_t**pptr)
{
    bbh_config_t*p = (bbh_config_t*)malloc(sizeof(bbh_config_t));
    memset(p, 0, sizeof(bbh_config_t));
    *pptr = p;
    return 0;
}
void bbh_config_init(bbh_config_t*_)
{
    memset(_, 0, sizeof(bbh_config_t));
    _->level = BBH_LEVEL_DEBUG;
    _->free_time_ms = 1000 * 10;
    _->file_rolling_interval = 24 * 3600;
}

int  bbh_config_set(bbh_config_t*_, const char*key, const char*value)
{
    int r = 0;
    if (0== strcasecmp(key, "level")) {
        _->level = value ? atoi(value) : BBH_LEVEL_DEBUG;
        if (_->level < BBH_LEVEL_DEBUG)
            _->level = BBH_LEVEL_DEBUG;
        if (_->level > BBH_LEVEL_FATAL)
            _->level = BBH_LEVEL_FATAL;
    } else if (0 == strcasecmp(key, "waitfordata_time")) {
        _->free_time_ms = atol(value);
    } else if (0 == strcasecmp(key, "pattern")) {
        if (_->pattern) {
            free(_->pattern);
            _->pattern = NULL;
        }
        if (value) {
            _->pattern = strdup(value);
        }
    } else if (0 == strcasecmp(key, "rolling_interval")) {
        _->file_rolling_interval = atoi(value);
        if (_->file_rolling_interval <= 0) {
            _->file_rolling_interval = 24 * 3600;
        }
    } else if (0 == strcasecmp(key, "rolling_size")) {
        _->file_rolling_size = atoi(value);
        if (_->file_rolling_size < 0) {
            _->file_rolling_size = 0;
        }
    } else if (0 == strcasecmp(key, "rolling_keep_num")) {
        _->file_rolling_keep_num = atoi(value);
        if (_->file_rolling_keep_num < 0) {
            _->file_rolling_keep_num = 0;
        }
    }
    return r;
}


void bbh_config_set_filepath(bbh_config_t*_, const char*filepath)
{
    _->file_path = strdup(filepath);
    char*s = strrchr(_->file_path, '/');
    if (s) {
        _->file_dir = _->file_path;
        *s++ = '\0';
    } else {
        s = _->file_path;
    }
    _->file_name = s;

    s = strrchr(s, '.');
    if (s) {
        *s++ = '\0';
        _->file_extname = s;
    }
}

void bbh_config_clear(bbh_config_t*_)
{
    free(_->file_path);
    free(_->pattern);
}

void bbh_config_free(bbh_config_t*_)
{
    bbh_config_clear(_);
    free(_);
}